// index.js
// 获取应用实例
//逻辑思路：
// 1.获取全部的经纬度
//2. 绘制线路
//3.设置定时器模拟线路

// this的指向有问题，当遇到request 的时候this 指向的是上下文，其实要保留page的this 改为_this
// 或者改为箭头函数



import { $request } from "../../utils/request"

// 创建一个音频实例对象
const audio=wx.createInnerAudioContext()


const app = getApp()

Page({
  data: {
    isFlag:true,
    num: 0,
    interval: "",
    isPlay: true,
    scale: 18,
    enable_traffic: true,
    show_compass: false,
    route: [],
    currentSceneIndex: -1, // 当前所在的景区索引
    currentAudioIndex: -1, // 当前所在的景区索引
    markers: [],
    scene:[],
      // 当前定位
    latitude:0,
    longitude:0,
    isPlayingAudio: false, // 添加音频播放状态变量
    destination: {
      latitude: 0, // 示例终点纬度
      longitude: 0 // 示例终点经度
    },
    userMarker: {
      id: 0,
      longitude: 0,
      latitude: 0,
      height: 40,
      width: 40
    },
    // 上次一次维度
    lastLatitude:0,
    lastLongitude:0,
    // 距离阈值，单位米
    distanceThreshold:10
  },



  rad (d){
    return d *Math.PI/180.0//计算弧度
  },
  getDistance (lat1,lng1,lat2,lng2){
   var R = 6378137; // 地球半径，单位为米
 var dLat = this.rad(lat2 - lat1);
 var dLon = this.rad(lng2 - lng1);
 var a = Math.sin (dLat / 2) * Math.sin (dLat / 2) +
             Math.cos (this.rad(lat1)) *Math.cos (this.rad(lat2))*
             Math.sin (dLon / 2) * Math.sin (dLon / 2);
 var c = 2 * Math.atan2 (Math.sqrt (a), Math.sqrt (1 - a));
 var d = R * c;
  return d;
 },

//关于景点的距离


//获取信息的
 
onShow(e) {
  var _this = this;
  _this.setData({
    isFlag: true,
  });
},

onLoad(options) {
  const id = app.getSelectId();
  var pointfor = [];
  console.log('Receive id', id); // id 拿到

  var _this = this;
  
//获取定位和线路之后 开始进行调用高德调用的api
  _this.getPostion().then(() => {
    // 确保 get_longitude 和 get_latitude 已经设置
    console.log('Position fetched:', _this.data.longitude, _this.data.latitude);

    // 最后一个点是最后一个景区  
    // 通过 wx.request 发起 HTTPS 接口请求
    Promise.all([_this.getrouteList(id), _this.getPostion()])
    .then(results => {
      console.log('Scene data:', _this.data.scene);
      _this.fetchRoute()
    })
    .catch(error => {
      console.error('Error fetching data:', error);
    });  // 监听音频播放结束事件
    audio.onEnded(() => {
      _this.setData({
        isPlayingAudio: false
      });
    });
  });
},

 // 获取当前地点的定位
 getPostion() {
  var _this = this;
  return new Promise((resolve, reject) => {
    wx.getLocation({
      type: 'gcj02', // 默认为 wgs84 返回 gps 坐标，gcj02 返回可用于 wx.openLocation 的坐标
      success(res) {
        const latitude = res.latitude;
        const longitude = res.longitude;
        _this.setData({
          latitude: latitude,
          longitude: longitude,
          ['userMarker.longitude']: longitude,
          ['userMarker.latitude']: latitude,
          
        });
        console.log('Current location:', latitude, longitude);
        resolve();
      },
      fail(err) {
        console.error('Error fetching position:', err);
        reject(err);
      }
    });
  });
},

//后端数据景点
getrouteList(id) {
    var _this = this;
    return new Promise((resolve, reject) => {
      $request({ url: `/route/miniprogram?id=${id}` }).then((res) => {
        console.log('res', res);
        
        var alongScenicAreaVO = res.data[0].alongScenicAreaVO;
        console.log('alongScenicAreaVO', alongScenicAreaVO);
        // 将全部的景点添加进去
     
        var scenes = alongScenicAreaVO.map(area => ({
          longitude: area.scenicAreaLongitude,
          latitude: area.scenicAreaLatitude,
          name: area.scenicAreaName, // 一个景点名称
          videoPath:area.scenicAreaVoice
        }));
        console.log(scenes)
        _this.setData({
          'destination.latitude': scenes[scenes.length - 1].latitude,
          'destination.longitude': scenes[scenes.length - 1].longitude
        })
    
          //创建景点标记
        var sceneMarkers = scenes.map((scene, index) => ({
          iconPath: "https://wechats.oss-cn-beijing.aliyuncs.com/location.png",
          id: 1+ index,
          longitude: scene.longitude,
          latitude: scene.latitude,
          height: 20,
          width: 20,
          label: {
            anchorY: -50,
            content: scene.name,
            padding: 5,
            fontSize: 12,
            textAlign: 'center',
            display: 'ALWAYS',
            borderRadius: 5,
            borderWidth: 1,
            bgColor: '#ffffff',
            borderColor: "#c3c3c3"
          },
        }));
          //更新markers数据
        _this.setData({
          scene: scenes,
          markers: _this.data.markers.concat(sceneMarkers) // 添加新的景点标记
        }, () => {
          console.log(_this.data.markers); // 打印 markers 以验证数据是否正确
          resolve(scenes);
        });
      }).catch(error => {
        console.error('Error fetching route list:', error);
        reject(error);
      });
    });
  },
  


  //绘制路线
    //通过位置并且绘制路线
  fetchRoute: function () {
    const that = this;
    const origin = `${that.data.longitude},${that.data.latitude}`;
    const destination = `${that.data.destination.longitude},${that.data.destination.latitude}`;
    if (that.data.scene && that.data.scene.length > 0) {
      console.log('Last scene coordinates:', that.data.scene[that.data.scene.length - 1].longitude, that.data.scene[that.data.scene.length - 1].latitude);
      // 构建途径点字符串
      let waypoints = that.data.scene.slice(0, -1).map(scene => `${scene.longitude},${scene.latitude}`).join(';');

      wx.request({
        url: `https://restapi.amap.com/v3/direction/driving`,
        data: {
          key: '21571ff7adb0223185347d34893558f3', // 替换为你的高德地图 API Key
          origin: origin,
          destination: destination,
          extensions: 'base',
          waypoints:waypoints,
          strategy: 0
        },
        success: function (res) {
          console.log('API Response:', res.data); // 添加日志输出
  
          if (res.data.status === '1' && res.data.route) {
            const route = res.data.route;
            const paths = route.paths;
            const steps = paths[0].steps;
            const polylinePoints = [];
             // 添加起点
          polylinePoints.push({
            longitude: parseFloat(origin.split(',')[0]),
            latitude: parseFloat(origin.split(',')[1])
          })
  
            for (let i = 0; i < steps.length; i++) {
              const polylines = steps[i].polyline.split(';');
              for (let j = 0; j < polylines.length; j++) {
                const point = polylines[j].split(',');
                polylinePoints.push({
                  longitude: parseFloat(point[0]),
                  latitude: parseFloat(point[1])
                });
              }
            }
            // 添加终点
          polylinePoints.push({
            longitude: parseFloat(destination.split(',')[0]),
            latitude: parseFloat(destination.split(',')[1])
          });
  
            that.setData({
              polyline: [{
                points: polylinePoints,
                color:  '#58c16c',
                width: 6,
                borderColor: '#2f693c',
                borderWidth: 1
              }]
            });
          } else {
            console.error('API Error:', res.data.info || 'Unknown error');
          }
        },
        fail: function (err) {
          console.error('请求路线失败', err);
        }
      });
  }
},

  startLocationUpdate: function () {
    const that = this;
    wx.startLocationUpdate({
      success: function () {
        wx.onLocationChange(function (res) {
          const latitude = res.latitude;
          const longitude = res.longitude;
           // 计算当前位置与上次位置之间的距离
           const distance = that.getDistance(that.data.lastLatitude, that.data.lastLongitude, latitude, longitude);

           // 如果距离超过阈值，则重新绘制路线
           if (distance > that.data.distanceThreshold) {
             console.log('User has moved more than the threshold. Redrawing route...，超出距离重新规划');
             that.fetchRoute();
           }
 
          that.setData({
            ['userMarker.longitude']: longitude,
            ['userMarker.latitude']: latitude,
           // markers: [that.data.userMarker] // 更新 markers 数组
          });
          that.checkPlayAduio(latitude,longitude)
        });
      },
      fail: function (err) {
        console.error('开启位置更新失败', err);
      }
    });
  },
  checkPlayAduio: function (latitude, longitude) {
    const that = this;
    const currentSceneIndex = that.data.currentSceneIndex + 1;
  if (currentSceneIndex >= that.data.scene.length) {
    return; // 如果已经播放完所有景点的语音，退出
  }

  const nextScene = that.data.scene[currentSceneIndex];
  const distanceToNextScene = that.getDistance(latitude, longitude, nextScene.latitude, nextScene.longitude);

  if (distanceToNextScene <= that.data.distanceThreshold && that.data.currentAudioIndex !== currentSceneIndex) {
    // 播放音频
    audio.src = nextScene.videoPath; // 设置音频源
    audio.play();
    that.setData({
      isPlayingAudio: true,
      currentAudioIndex: currentSceneIndex // 更新当前正在播放的景点索引
    });

    // 监听音频播放结束事件
    audio.onEnded(() => {
      that.setData({
        isPlayingAudio: false
      });
      // 更新当前景点索引以便播放下一个景点的语音
      that.setData({
        currentSceneIndex: currentSceneIndex
      });
    });
  }
},


 
  onHide(e){
 
    audio.stop() // 暂停
    audio.destroy(); // 销毁音频上下文
    var _this = this
    _this.setData({
      // 将路线的起点设置为地图中心点
      isFlag:false,
      isPlayingAudio: false,
    })
    // _this.clearTimer();
  },

  onReady:function(){
    this.startLocationUpdate();
  },


  onUnload(e){
    const that = this;
    audio.stop(); // 停止之前的音频
    // audio.destroy(); // 销毁音频上下文
    that.setData({
      isFlag:false,
      isPlayingAudio: false,
    })
    wx.stopLocationUpdate();

  },



  gotoPage:function () {
    wx.navigateTo({
      url: '../begin/begin', //要跳转到的页面路径
    })
  }
})